import { Provide } from "@midwayjs/decorator";
import { InjectEntityModel } from "@midwayjs/typegoose";
import { ReturnModelType } from "@typegoose/typegoose";
import { Thumb } from "../entity/thumb";
import { RespInfo } from "../types/common.type";
import { ThumbType } from "../types/thumb.type";
import { RespMethod } from "../util/common.method";


@Provide()
export class ThumbService {

  @InjectEntityModel(Thumb)
  thumbModel: ReturnModelType<typeof Thumb>;

  /** 点赞或点踩 */
  async setThumb(user: string, target: string, type: ThumbType): Promise<RespInfo> {
    const thumb = await this.thumbModel.findOne({ target, user });
    if (thumb) {
      await this.thumbModel.updateOne({ type }).where({ target, user })
    } else {
      await this.thumbModel.create({ target, user, type })
    }
    const count = await this.getCountByTarget(target);
    const info = { type, count }
    return RespMethod({ info })
  }

  /**
   * 获取某个状态的数量
   * @param target 
   * @param type 
   * @returns 
   */
  async getCountByTarget(target: string, type: ThumbType = ThumbType.Up): Promise<number> {
    const list = await this.thumbModel.find({ target, type });
    return list?.length || 0;
  }

  async getThumbTypeByUser(target: string, user: string): Promise<ThumbType> {
    const info = await this.thumbModel.findOne({ target, user })
    return info?.type || ThumbType.Default;
  }
}